package com.example.xinli.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.xinli.AboutUsActivity;
import com.example.xinli.MainActivity;
import com.example.xinli.PrivacyActivity;
import com.example.xinli.R;
import com.example.xinli.UpdatePasswordActivity;
import com.example.xinli.UserDbHelper;
import com.example.xinli.UserInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MeFragment extends Fragment {
    private View rootView;
    private TextView usernameT;
    private TextView nicknameT;
    private RelativeLayout aboutusRL;
    private RelativeLayout privacyRL;
    private RelativeLayout updateRL;
    private String currentUsername; // 保存当前用户名
    private UserInfo currentUserInfo; // 保存当前用户完整信息
    private ImageView avatarImageView;

    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_IMAGE_CAPTURE = 1002;
    private static final int REQUEST_PERMISSION = 1003;
    private static final int REQUEST_IMAGE_CROP = 1003;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_me, container, false);

        usernameT = (TextView) rootView.findViewById(R.id.usernameTV);
        nicknameT = (TextView) rootView.findViewById(R.id.nicknameTV);
        avatarImageView = (ImageView) rootView.findViewById(R.id.picture);

        // 设置头像点击事件
        if (avatarImageView != null) {
            avatarImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAvatarSelectionDialog();
                }
            });
        }

        rootView.findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded() && getActivity() != null) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle("温馨提示")
                            .setMessage("确定要退出登录吗？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    getActivity().finish();
                                    Intent intent = new Intent(getActivity(), MainActivity.class);
                                    startActivity(intent);
                                }
                            })
                            .create();
                    alertDialog.show();
                }
            }
        });

        aboutusRL = (RelativeLayout) rootView.findViewById(R.id.aboutusRL);
        if (aboutusRL != null) {
            aboutusRL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    aboutus(view);
                }
            });
        }

        privacyRL = (RelativeLayout) rootView.findViewById(R.id.privacyRL);
        if (privacyRL != null) {
            privacyRL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isAdded() && getActivity() != null) {
                        Intent intent = new Intent(getActivity(), PrivacyActivity.class);
                        startActivity(intent);
                    }
                }
            });
        }

        updateRL = (RelativeLayout) rootView.findViewById(R.id.updateRL);
        if (updateRL != null) {
            updateRL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 确保用户名不为空再跳转
                    if (isAdded() && getActivity() != null && currentUsername != null && !currentUsername.isEmpty()) {
                        Intent intent = new Intent(getActivity(), UpdatePasswordActivity.class);
                        intent.putExtra("username", currentUsername);
                        startActivityForResult(intent, 1000);
                    } else if (isAdded() && getActivity() != null) {
                        Toast.makeText(getActivity(), "用户信息获取失败，请重新登录", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        // 添加昵称编辑点击事件
        View editNickname = rootView.findViewById(R.id.editNickname);
        if (editNickname != null) {
            editNickname.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditNicknameDialog();
                }
            });
        }

        // 点击昵称区域也可以编辑
        if (nicknameT != null) {
            nicknameT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditNicknameDialog();
                }
            });
        }

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次Fragment可见时都尝试加载用户信息
        if (isAdded() && currentUsername != null && !currentUsername.isEmpty()) {
            loadUserInfoFromDatabase(currentUsername);
            loadAvatar(); // 加载用户头像
        }
    }

    // 从数据库加载用户信息
    private void loadUserInfoFromDatabase(String username) {
        try {
            if (isAdded() && getContext() != null) {
                UserInfo userInfo = UserDbHelper.getInstance(getContext()).login(username);
                if (userInfo != null) {
                    this.currentUserInfo = userInfo;
                    if (usernameT != null) usernameT.setText(userInfo.getUsername());
                    if (nicknameT != null) nicknameT.setText(userInfo.getNickname());
                } else {
                    if (usernameT != null) usernameT.setText("用户不存在");
                    if (nicknameT != null) nicknameT.setText("请重新登录");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (usernameT != null) usernameT.setText("加载失败");
            if (nicknameT != null) nicknameT.setText("请重新登录");
        }
    }

    // 显示编辑昵称对话框
    private void showEditNicknameDialog() {
        if (!isAdded() || getActivity() == null) return;

        if (currentUserInfo == null) {
            Toast.makeText(getActivity(), "请先加载用户信息", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("修改个性签名");

        final EditText input = new EditText(getContext());
        input.setText(currentUserInfo.getNickname());
        builder.setView(input);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isAdded() && getActivity() != null) {
                    String newNickname = input.getText().toString().trim();
                    if (!newNickname.isEmpty()) {
                        updateNicknameInDatabase(newNickname);
                    } else {
                        Toast.makeText(getActivity(), "不能为空", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }

    // 更新昵称到数据库
    private void updateNicknameInDatabase(String newNickname) {
        try {
            if (isAdded() && getContext() != null && currentUserInfo != null) {
                int result = UserDbHelper.getInstance(getContext()).updateNickname(
                        currentUserInfo.getUsername(), newNickname);

                if (result > 0) {
                    // 更新成功，更新界面显示
                    currentUserInfo.setNickname(newNickname);
                    if (nicknameT != null) nicknameT.setText(newNickname);
                    if (isAdded() && getActivity() != null) {
                        Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                    }
                } else if (isAdded() && getActivity() != null) {
                    Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (isAdded() && getActivity() != null) {
                Toast.makeText(getActivity(), "修改失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void aboutus(View view) {
        if (isAdded() && getActivity() != null) {
            Intent intent = new Intent(getActivity(), AboutUsActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (!isAdded() || getActivity() == null) return;

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_PICK:
                    if (data != null && data.getData() != null) {
                        Uri imageUri = data.getData();
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
                            saveAvatar(bitmap);
                            if (avatarImageView != null) {
                                avatarImageView.setImageBitmap(bitmap);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;

                case REQUEST_IMAGE_CAPTURE:
                    if (data != null && data.getExtras() != null) {
                        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                        if (bitmap != null) {
                            saveAvatar(bitmap);
                            if (avatarImageView != null) {
                                avatarImageView.setImageBitmap(bitmap);
                            }
                        }
                    }
                    break;
            }
        }

        if (requestCode == 1000 && resultCode == 1000) {
            // 密码修改成功，重新加载用户信息
            if (currentUsername != null && !currentUsername.isEmpty()) {
                loadUserInfoFromDatabase(currentUsername);
            }
        }
    }

    // 提供给外部Activity调用的方法，用于设置当前用户
    public void setCurrentUser(String username) {
        this.currentUsername = username;
        // 立即加载用户信息
        if (isAdded()) {
            loadUserInfoFromDatabase(username);
            loadAvatar(); // 加载用户头像
        }
    }

    // 显示头像选择对话框
    private void showAvatarSelectionDialog() {
        if (!isAdded() || getActivity() == null) return;

        // 检查权限
        if (checkPermission()) {
            showAvatarSelectionOptions();
        } else {
            requestPermission();
        }
    }

    // 检查权限
    private boolean checkPermission() {
        if (!isAdded() || getContext() == null) return false;

        return ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED &&
               ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
    }

    // 请求权限
    private void requestPermission() {
        if (!isAdded() || getActivity() == null) return;

        ActivityCompat.requestPermissions(getActivity(),
                new String[]{
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.CAMERA
                },
                REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION && isAdded() && getActivity() != null) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showAvatarSelectionOptions();
            } else {
                Toast.makeText(getContext(), "需要权限才能更换头像", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 显示头像选择选项
    private void showAvatarSelectionOptions() {
        if (!isAdded() || getContext() == null) return;

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("选择头像");
        String[] options = {"从相册选择", "拍照"};

        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!isAdded() || getActivity() == null) return;

                switch (which) {
                    case 0: // 从相册选择
                        openGallery();
                        break;
                    case 1: // 拍照
                        openCamera();
                        break;
                }
            }
        });

        builder.show();
    }

    // 打开相册选择图片
    private void openGallery() {
        if (!isAdded() || getActivity() == null) return;

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }

    // 打开相机拍照
    private void openCamera() {
        if (!isAdded() || getActivity() == null) return;

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
        } else {
            Toast.makeText(getContext(), "无法启动相机", Toast.LENGTH_SHORT).show();
        }
    }

    // 保存头像到本地
    private void saveAvatar(Bitmap bitmap) {
        if (!isAdded() || getContext() == null || currentUsername == null) return;

        try {
            // 创建头像文件路径
            File avatarDir = new File(getContext().getFilesDir(), "avatars");
            if (!avatarDir.exists()) {
                avatarDir.mkdirs();
            }

            String avatarPath = new File(avatarDir, currentUsername + "_avatar.png").getAbsolutePath();

            // 压缩并保存图片
            FileOutputStream out = new FileOutputStream(avatarPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
            if (isAdded() && getActivity() != null) {
                Toast.makeText(getContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 加载用户头像
    private void loadAvatar() {
        if (!isAdded() || getContext() == null) return;

        if (currentUsername != null && !currentUsername.isEmpty()) {
            File avatarFile = new File(getContext().getFilesDir(), "avatars/" + currentUsername + "_avatar.png");
            if (avatarFile.exists() && avatarImageView != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getAbsolutePath());
                if (bitmap != null) {
                    avatarImageView.setImageBitmap(bitmap);
                }
            }
        }
    }
}
